import 'dart:async';
import 'package:pure/model.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' show join;
import 'package:uuid/uuid.dart';

/// 数据库处理
class DataBaseUtil {
  static String createVodSourceSql = '''
      create table $vodSourceTable(
        id text primary key,
        name text,
        base text,
        sync integer,
        vod_total integer,
        vod_count integer
      )
  ''';

  static String createVodSql = '''
      create table $vodTable(
        id text primary key,
        vod_id integer,
        type_name text,
        vod_sub text,
        vod_class text,
        vod_pic text,
        vod_pic_thumb text,
        vod_actor text,
        vod_director text,
        vod_writer text,
        vod_blurb text,
        vod_area text,
        vod_lang text,
        vod_year text,
        vod_remarks text,
        vod_play_url text,
        vod_time_add text,
        vod_time text,
        vod_score text,
        vod_play_from text
      )
  ''';

  static const vodTable = 'p_vod';

  static const vodSourceTable = 'p_vod_source';

  static Database? _database;

  static int version = 2;

  static String dbName = 'pure.db';

  static String firstRun = 'first_run';

  static String currentSource = 'current_source';

  static Uuid uuid = const Uuid();

  static SharedPreferences? prefs;

  static init() async {
    prefs = await SharedPreferences.getInstance();
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, dbName);
    _database = await openDatabase(path, version: version,
        onCreate: (Database db, int version) async {
      Future createVod(Database database) async {
        await database.execute(createVodSql);
      }

      Future createVodSource(Database database) async {
        await database.execute(createVodSourceSql);
      }

      await createVod(db);
      await createVodSource(db);
      // 内置数据
      // 创建表
    }, onUpgrade: (Database db, int oldVersion, int newVersion) {
      // 更新表
    }, onDowngrade: (Database db, int oldVersion, int newVersion) {
      // 更新表
    });
  }

  // 保存、更新
  static saveVod(Vod vod) {
    if (!vod.id.hasValue) {
      vod.id.v = uuid.v4();
      _database!.insert(vodTable, vod.toMap());
    } else {
      _database!.update(vodTable, vod.toMap(),
          conflictAlgorithm: ConflictAlgorithm.replace);
    }
  }

  // 批量保存
  static saveBatchVod(List<Vod> vods) {
    final batch = _database!.batch();
    for (var element in vods) {
      batch.insert(vodTable, element.toMap(),
          conflictAlgorithm: ConflictAlgorithm.replace);
    }
    batch.commit();
  }

  // 删除
  static delVod(String id) {
    _database!.delete(vodTable, where: 'id=?', whereArgs: [id]);
  }

  // 分页、搜索
  static Future<List<Vod>> listVod(
      {int limit = 20, int offset = 0, String search = ''}) async {
    String where = '''1=1''';
    if (search.isEmpty) {
      where += '''and name like "%$search%"''';
    }
    final res = await _database!.query(vodTable,
        where: where, limit: limit, offset: offset, orderBy: 'timeAdd desc');
    if (res.isEmpty) return [];
    return List.generate(res.length, (index) => Vod()..fromMap(res[index]));
  }

  // 保存、更新
  static Future saveVodSource(VodSource source) async {
    if (!source.id.hasValue) {
      source.id.v = uuid.v4();
      await _database!.insert(vodSourceTable, source.toMap(),conflictAlgorithm: ConflictAlgorithm.replace);
    } else {
      await _database!.update(vodSourceTable,where: 'id=?',whereArgs: [source.id.v], source.toMap(),conflictAlgorithm: ConflictAlgorithm.replace);
    }
  }

  // 删除
  static Future delVodSource(String id) async {
    await _database!.delete(vodSourceTable, where: 'id=?', whereArgs: [id]);
  }

  // 分页、搜索
  static Future<List<VodSource>> listVodSource() async {
    final res = await _database!.query(vodSourceTable);
    if (res.isEmpty) return [];
    return List.generate(
        res.length, (index) => VodSource()..fromMap(res[index]));
  }
}
